import { request } from "../request";
import { getApiKey } from "../request";

export const userApi = {
  // 用户登录
  login: (username, password, mfacode) => {
    return request(
      "/api/getKey",
      "POST",
      { nameOrEmail: username, userPassword: password, mfaCode: mfacode },
      false
    );
  },

  // 注册 - 获取短信验证码
  register: (data) => {
    return request("/register", "POST", data, false);
  },

  // 验证短信验证码
  verifySmsCode: (code) => {
    return request(`/verify?code=${code}`, "GET", null, false);
  },

  // 设定密码和邮箱
  completeRegister: (data, inviteUser) => {
    return request(`/register2?r=${inviteUser || ""}`, "POST", data, false);
  },
  //更新头像
  updateAvatar: (userAvatarURL) => {
    return request("/settings/avatar", "POST", { userAvatarURL });
  },
  // 获取当前用户信息
  getCurrentUser: () => {
    return request("/api/user");
  },
  //查询用户背包
  getUserBag: (userName) => {
    return request("/user/query/items", "POST", { userName });
  },
  // 获取用户资料
  getProfile: (username) => {
    return request(`/user/${username}`, "GET");
  },

  // 更新用户个人资料
  updateProfile: (data) => {
    return request("/api/user", "PUT", data);
  },

  // 获取活跃度
  getActive: () => {
    return request("/user/liveness", "GET");
  },

  // 查询最近注册的20个用户
  getRecentRegisteredUsers: () => {
    return request("/api/user/recentReg", "GET");
  },

  // 转账
  transfer: (userName, amount, memo) => {
    return request("/point/transfer", "POST", { userName, amount, memo });
  },

  // 关注用户
  followUser: (followingId) => {
    return request(`/follow/user`, "POST", { followingId });
  },

  // 取消关注用户
  unfollowUser: (followingId) => {
    return request(`/unfollow/user`, "POST", { followingId });
  },
  //上传图片或视频
  //限制
  //大小：<=20M，
  //文件格式：jpg, jpeg, png, gif, mp4
  //请求类型：multipart/form-data
  uploadImage: (file) => {
    return new Promise((resolve, reject) => {
      const apiKey = getApiKey();
      if (!apiKey) {
        reject(new Error("未登录"));
        return;
      }

      // 获取文件名
      const fileName = file.split("/").pop();

      uni.uploadFile({
        url: `https://fishpi.cn/upload`,
        filePath: file,
        name: "file[]",
        formData: {
          apiKey: apiKey,
        },
        header: {
          "Content-Type": "multipart/form-data",
        },
        success: (res) => {
          console.log("上传响应:", res);
          if (res.statusCode === 200) {
            try {
              const data = JSON.parse(res.data);
              console.log("解析后的响应数据:", data);

              if (data.code === 0) {
                // 检查是否有上传失败的文件
                if (
                  data.data &&
                  data.data.errFiles &&
                  data.data.errFiles.length > 0
                ) {
                  reject(
                    new Error(`文件 ${data.data.errFiles.join(", ")} 上传失败`)
                  );
                  return;
                }

                // 检查上传成功的文件
                if (
                  data.data &&
                  data.data.succMap &&
                  Object.keys(data.data.succMap).length > 0
                ) {
                  const fileUrl = data.data.succMap[fileName];
                  if (fileUrl) {
                    resolve({
                      code: 0,
                      msg: "",
                      data: {
                        succMap: {
                          [fileName]: fileUrl,
                        },
                      },
                    });
                  } else {
                    reject(new Error("未找到上传文件的URL"));
                  }
                } else {
                  reject(new Error("上传失败：未获取到文件URL"));
                }
              } else {
                reject(new Error(data.msg || "上传失败"));
              }
            } catch (e) {
              console.error("解析响应数据失败:", e);
              reject(new Error("解析响应数据失败"));
            }
          } else {
            console.error("上传失败，状态码:", res.statusCode);
            reject(new Error(`上传失败，状态码: ${res.statusCode}`));
          }
        },
        fail: (err) => {
          console.error("上传请求失败:", err);
          reject(err);
        },
      });
    });
  },

  // 获取一句话
  getOneQuote: () => {
    return new Promise((resolve, reject) => {
      uni.request({
        url: "https://api.dwo.cc/api/yi",
        method: "GET",
        success: (res) => {
          if (res.statusCode === 200) {
            resolve(res.data);
          } else {
            reject(new Error("获取一句话失败"));
          }
        },
        fail: (err) => {
          reject(err);
        },
      });
    });
  },
};
